package cn.qu.phizline.webserver.ws;

import cn.qu.phizline.common.TypeUtils;
import cn.qu.phizline.event.Payload;
import cn.qu.phizline.webserver.event.WebPayloadConventer;
import cn.qu.phizline.webserver.event.handle.Handle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

/**
 * Created by zh on 17/8/23.
 */
public class WebServerHandle extends AbstractWebSocketHandler {

    @Autowired
    private WebServer webServer;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message)
            throws Exception {

        byte[] bytes = message.getPayload().array();

        Payload payload = webServer.load(bytes);

        Class<? extends Handle> handleType = webServer.getHandleType(payload.getType(), payload.getVersion());
        Handle handle = TypeUtils.newInstance(handleType);

        applicationContext.getAutowireCapableBeanFactory().autowireBean(handle);

        Payload result = handle.handle(payload);
        byte[] resultBytes = new WebPayloadConventer().toBytes(result);
        session.sendMessage(new BinaryMessage(resultBytes));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(message);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }
}
